<!-- echart 柱状图 -->
<template>
  <div id="echarts" ref="echartsBar" class="box" />
</template>

<script>
import echarts from "echarts";
import { formatMoney } from "@/utils/common.js";
import { mapGetters } from "vuex";
import variables from "@/styles/black/variables.scss";
const options = {
  tooltip: {
    trigger: "axis",
    backgroundColor: variables.tooptipBgColor,
    axisPointer: {
      type: "shadow",
      label: {
        show: true,
      },
    },
  },
  title: {
    show: false,
    text: "",
  },
  toolbox: {
    show: true,
    top: 10,
    right: 20,
    showTitle: false,
    iconStyle: {
      borderColor: variables.iconColor,
    },
    feature: {
      saveAsImage: {
        show: true,
        excludeComponents: ["toolbox"],
        pixelRatio: 2,
        backgroundColor: variables.linehightColor,
      },
    },
  },
  calculable: true,
  animation: true,
  legend: {
    type: "scroll",
    orient: "horizontal",
    pageIconColor: variables.iconColor,
    pageIconInactiveColor: variables.linehightColor,
    pageTextStyle: {
      color: variables.textColor,
    },
    width: 450,
    data: [],
    formatter: function(name) {
      // console.log(name, "name");
      // options.legend.selected[name] = false;
      // console.log(options, "options");
      return name;
    },
    selected: {},
    itemGap: 10,
    itemWidth: 14,
    itemHeight: 14,
    // left: "55%",
    right: 60,
    top: 15,
    // top: "2%",
    // bottom: '10%'
    // selectedMode: false,
    icon: "rect",
    textStyle: {
      fontSize: 12,
      borderRadius: 2,
    },
  },
  grid: {
    top: "20%",
    left: "8%",
    right: "3%",
    bottom: "10%",
    // containLabel: true,
  },
  xAxis: [
    {
      type: "category",
      // splitNumber: 100
      data: [],
      nameTextStyle: {
        color: variables.textColor,
      },
      axisLabel: {
        interval: "auto",
        color: variables.textColor,
      },
      axisLine: {
        show: true,
        lineStyle: {
          color: variables.xyLineBgColor,
          width: 1,
          type: "solid",
        },
      },
    },
  ],
  yAxis: [],
  dataZoom: [
    {
      type: "inside",
      start: 50,
      end: 80,
      // minSpan: 10,
      // maxSpan: 20,
      // disabled:false,
      throttle: 500,
    },
  ],
  series: [],
};
export default {
  name: "",
  components: {},
  props: {
    checkList: {
      type: Array,
      default: () => {},
    },
    sortCheckData: {
      type: Array,
      default: () => {},
    },
    list: {
      type: Array,
      default: () => {},
    },
    echartsData: {
      type: Object,
      default: () => {},
    },
    xDataSort: {
      type: Array,
      default: () => {},
    },
    echartsTitle: {
      type: String,
      default: () => {},
    },
    barName: {
      type: Array,
      default: () => {},
    },
  },
  data() {
    return {
      echarts1: null,
      name: [],
    };
  },
  computed: {
    // 监听store中数据变化
    ...mapGetters(["isCollapse"]),
    menuIsCollapse() {
      return this.isCollapse;
    },
  },
  watch: {
    menuIsCollapse: {
      handler(newValue, oldValue) {
        console.log("echart watch isCollapse", newValue, oldValue);
        this.getData();
      },
      deep: true,
    },
    checkList: {
      handler(newValue, oldValue) {
        this.getData();
      },
      deep: true,
    },
    sortCheckData: {
      handler(newValue, oldValue) {
        this.getData();
      },
      deep: true,
    },
    echartsData: {
      handler: function(newValue, oldValue) {
        this.getData();
      },
      deep: true,
      // immediate: true
    },
    xDataSort: {
      handler: function(newValue, oldValue) {
        this.getData();
        // options.xAxis[0].data = [];
        // this.echartsData.xdate.forEach(item => {
        //   let arr = [];
        //   newValue.forEach(item1 => {
        //     // let str = item[item1.column];
        //     if (item[item1.column]) {
        //       arr.push(item[item1.column]);
        //     }
        //   });
        //   let str = arr.join(",").replace(/,/g, "-");
        //   options.xAxis[0].data.push(str);
        //   // console.log(str);
        // });
      },
      deep: true,
    },
  },
  created() {},
  mounted() {
    this.getData();
    window.onresize = () => {
      this.getData();
    };
    window.addEventListener("resize", () => {
      this.getData();
    });
  },
  activated() {
    this.getData();
  },
  beforeDestroy() {
    // console.log("组件销毁beforeDestroy");
    if (this.echarts1) {
      this.echarts1.clear();
    }
  },
  destroyed() {
    // console.log("组件销毁destroyed");

    if (this.echarts1) {
      this.echarts1.dispose();
    }
  },
  // deactivated() {
  //   console.log("deactivated页面关闭时触发");
  // },
  methods: {
    getData() {
      this.name = this.list.map((item) => item.name);
      // console.log(this.name, "name");
      const serArr = [];
      const lenArr = [];
      const yArr = [];
      const seriesData = [];
      const lengdData = [];
      const yAxis = [];
      this.list.forEach((item, index) => {
        const obj = {
          name: item.name,
          type: "bar",
          yAxisIndex: index,
          barMaxWidth: 15,
          label: {
            name: item.unit,
          },
          itemStyle: {
            normal: {
              barBorderRadius: [2, 2, 2, 2],
              color: new echarts.graphic.LinearGradient(
                0,
                1,
                0,
                0,
                [
                  {
                    offset: 0,
                    color: item.color0, // 0% 处的颜色
                  },
                  {
                    offset: 1,
                    color: item.color1, // 100% 处的颜色
                  },
                ],
                false
              ),
            },
          },
          // data: []
          data: this.echartsData[item.acronym]
            ? this.echartsData[item.acronym]
            : [],
        };
        const len = {
          name: item.name,
          textStyle: {
            color: variables.textColor,
          },
        };
        const yax = {
          id: index,
          show: true,
          type: "value",
          axisLabel: {
            // show: true
            formatter: function(value, index) {
              // return value > 1000 ? value / 10000 + "w" : value;
              if (value > 1000 || value < -1000) {
                return value / 10000 + "w";
              } else {
                return value;
              }
            },
          },
          // 刻度的间隔
          // interval: 20,
          name: item.unit,
          offset: 0 * 40,
          position: "left",
          nameTextStyle: {
            color: item.color1,
          },
          nameGap: 23,
          // nameLocation:'end',
          // 设置y轴
          axisLine: {
            show: true,
            lineStyle: {
              color: item.color1,
              width: 1,
              type: "solid",
            },
          },
          // 设置y轴的刻度线
          axisTick: {
            // show: index == 1 ? true : false,
            show: true,
            inside: true,
            lineStyle: {
              type: "solid",
            },
          },
          // 设置背景线为虚线
          splitLine: {
            // show: index == 1 ? true : false,
            show: false,
            lineStyle: {
              type: "dashed",
            },
          },
        };
        seriesData.push(obj);
        lengdData.push(len);
        yAxis.push(yax);
      });
      // console.log(seriesData, "seriesData");
      // console.log(this.checkList.length);
      if (this.checkList.length != 0) {
        seriesData.forEach((item) => {
          if (this.checkList.indexOf(item.name) != -1) {
            serArr.push(item);
          } else {
            if (
              this.echartsTitle == "投资人" &&
              this.barName.indexOf(item.name) != -1
            ) {
              serArr.push(item);
            }
          }
        });
        lengdData.map((item) => {
          if (this.checkList.indexOf(item.name) != -1) {
            lenArr.push(item);
          } else {
            this.checkList.forEach((str) => {
              // console.log(str,'item-name',item.name);
              if (item.name.indexOf(str) != -1) {
                lenArr.push(item);
              }
            });
          }
        });
        // console.log(serArr,'serarr');
        serArr.forEach((item, index) => {
          const name = item.name;
          if (this.name.indexOf(item.name) != -1) {
            const i = this.name.indexOf(item.name);
            item.yAxisIndex = index;
            if (index != 0) {
              yAxis[i].offset = index * 45;
            } else {
              // yAxis[i].axisTick.show = true;
              yAxis[i].splitLine.show = true;
              yAxis[i].offset = 0;
            }
            yArr.push(yAxis[i]);
          }
        });
        // console.log(yArr, "yArr");
        if (this.sortCheckData.length != 0) {
          if (this.sortCheckData.length == this.list.length) {
            // 分析数据的排序
            const sortSerArr = [];
            const sortLenArr = [];
            const sortyAxis = [];
            this.sortCheckData.forEach((item, index) => {
              serArr.forEach((item1, index1) => {
                if (item == item1.name) {
                  sortSerArr.push(item1);
                }
              });
              lenArr.forEach((item2, index2) => {
                if (item == item2.name) {
                  sortLenArr.push(item2);
                }
              });
            });
            // console.log(sortSerArr,'sortSerArr');
            sortSerArr.forEach((item, index) => {
              // 0 债券指数 1 分销金额 2 销售佣金 3 只数占比 4 算数平均费率 5 分销金额占比
              // let this.name = ['债券只数','分销金额','销售佣金','算数平均费率','只数占比','分销金额占比']
              if (this.name.indexOf(item.name) != -1) {
                const i = this.name.indexOf(item.name);
                item.yAxisIndex = index;
                if (index != 0) {
                  // yAxis[i].axisTick.show = false;
                  yAxis[i].splitLine.show = false;
                  yAxis[i].offset = index * 45;
                } else {
                  // yAxis[i].axisTick.show = true;
                  yAxis[i].splitLine.show = true;
                  yAxis[i].offset = 0;
                }
                sortyAxis.push(yAxis[i]);
              }
            });
            options.series = sortSerArr;
            options.legend.data = sortLenArr;
            options.yAxis = sortyAxis;
            // console.log(options.series, "options.series");
            // options.xAxis[0].data = this.echartsData.xdate;
          } else if (this.echartsTitle == "投资人") {
            const sortSerArr = [];
            const sortLenArr = [];
            const sortyAxis = [];
            this.sortCheckData.forEach((item, index) => {
              serArr.forEach((item1, index1) => {
                // console.log(item1.name.includes(item),'----',item1.name,'---',item);
                if (item1.name.includes(item)) {
                  sortSerArr.push(item1);
                }
              });
              lenArr.forEach((item2, index2) => {
                if (item2.name.includes(item)) {
                  sortLenArr.push(item2);
                }
              });
            });
            // console.log(sortSerArr,'sortSerArr');
            const colors = [
              // { color0: "#296BCD", color1: "#579BFF" },
              // { color0: "#F19439", color1: "#FFCB98" },
              // { color0: "#2047B6", color1: "#A686FF" },
              // { color0: "#299BCD", color1: "#57F9FF" },
              // { color0: "#49DA7C", color1: "#B8FB68" },
              // { color0: "#A568DF", color1: "#B983DF" },
              { color0: "#0CA1FF", color1: "#0CE0FF" },
              { color0: "#6FE7FB", color1: "#43BCD0" },
              { color0: "#ABD998", color1: "#7AB064" },
              { color0: "#7098FC", color1: "#3D64C3" },
              { color0: "#AE850B", color1: "#F5D078" },
              { color0: "#BD490B", color1: "#FD8C47" },
            ];
            sortSerArr.forEach((item, index) => {
              item.itemStyle.normal.color.colorStops[0].color =
                colors[index].color0;
              item.itemStyle.normal.color.colorStops[1].color =
                colors[index].color1;
              if (this.name.indexOf(item.name) != -1) {
                const i = this.name.indexOf(item.name);
                item.yAxisIndex = index;
                if (index != 0) {
                  yAxis[i].splitLine.show = false;
                  yAxis[i].offset = index * 45;
                } else {
                  yAxis[i].splitLine.show = true;
                  yAxis[i].offset = 0;
                }
                sortyAxis.push(yAxis[i]);
              }
            });
            sortyAxis.forEach((item, index) => {
              item.axisLine.lineStyle.color = colors[index].color1;
              item.nameTextStyle.color = colors[index].color1;
            });
            options.series = sortSerArr;
            options.legend.data = sortLenArr;
            options.yAxis = sortyAxis;
            // console.log(options,'options');
          } else {
            options.series = serArr;
            options.legend.data = lenArr;
            options.yAxis = yArr;
            // console.log(options,'options');
            // options.xAxis[0].data = this.echartsData.xdate;
          }
        } else {
          options.series = serArr;
          options.legend.data = lenArr;
          options.yAxis = yArr;
          // options.xAxis[0].data = this.dataArr;
        }
        let y = 3;
        let g = 7.5;
        // console.log(window.innerWidth, "innerWidth");
        if (window.innerWidth <= 1680 && window.innerWidth > 1380) {
          y = 3.8;
          g = 8.5;
        } else if (window.innerWidth <= 1745 && window.innerWidth > 1680) {
          y = 3.3;
          g = 8.5;
        } else if (window.innerWidth < 1380) {
          y = 5;
          g = 9.5;
        } else if (window.innerWidth > 1920 && window.innerWidth <= 2133) {
          y = 2.8;
          g = 7.5;
        } else if (window.innerWidth > 2133) {
          y = 2.5;
          g = 7.5;
        }
        if (yArr.length == 2) {
          yArr[1].position = "right";
          yArr[1].offset = 0;
          yArr[0].offset = 0;
          options.grid.left = y + "%";
          options.grid.right = y + 1 + "%";
        } else if (yArr.length == 1) {
          options.grid.left = y + "%";
        } else {
          options.grid.left = y * yArr.length - 0.5 + "%";
        }
        // options.legend.left = 100 - g * lenArr.length + "%";
        // console.log(g, "gggggg");
        // console.log(options.legend.left, "options.legend.left");
        if (yArr.length == 2) {
          // options.legend.left = "70%"
        }
        options.xAxis[0].data = [];
        this.echartsData.xdate.forEach((item) => {
          const arr = [];
          this.xDataSort.forEach((item1) => {
            // let str = item[item1.column];
            if (item[item1.column]) {
              arr.push(item[item1.column]);
            }
          });
          const str = arr.join(",").replace(/,/g, "-");
          options.xAxis[0].data.push(str);
        });
        // options.xAxis[0].data = this.echartsData.xdate;
        options.title.text = this.echartsData.title;
        this.echarts1 = echarts.init(document.getElementById("echarts"));
        this.echarts1.on("legendselectchanged", function(params) {
          let first = true;
          options.series.forEach((item, i) => {
            if (first && params.selected[item.name]) {
              first = false;
              options.yAxis[i].splitLine.show = true;
            } else {
              options.yAxis[i].splitLine.show = false;
            }
          });
          this.setOption(options);
        });
        if (
          options.series[0] &&
          options.series[0].data &&
          options.series[0].data.length <= 50
        ) {
          options.dataZoom[0].start = 0;
          options.dataZoom[0].end = 100;
        } else {
          options.dataZoom[0].start = 50;
          options.dataZoom[0].end = 60;
        }
        // console.log(options, "options");
        const title = this.echartsData.title;
        options.tooltip.formatter = function(params) {
          // console.log(params, "echarats-params");
          // console.log(window,'echarts-this  ');
          // console.log(this,'this');
          // console.log(title,'title');
          let res = "";
          let res1 = "";
          let lastName = "";
          const moneys = [
            "分销金额",
            "持仓量",
            // "算数平均票面1",
            "交易金额",
            "发行金额",
            "承销份额",
            "中标总量",
            "交易量",
            "估值模拟",
            "承销规模",
          ];
          const hour = [
            "平均持仓天数（自然日）",
            "最大持仓天数（自然日）",
            "平均持仓天数（工作日）",
            "最大持仓天数（工作日）",
            "最大持有天数",
            "平均持有天数",
            "最大处置时长",
            "平均处置时长",
          ];
          const money = [
            "总体销售佣金",
            "已收销售佣金",
            "应收销售佣金",
            "销售佣金",
            // "算数平均票面",
            "净承销费",
            "当日持仓利润",
            "累计持仓利润",
            "团费支出",
            "累计票息收入",
            "总体承销收入",
            "已收承销收入",
            "应收承销收入",
          ];
          const BP = [
            "算数平均费率",
            "算数平均销售佣金费率",
            "最大估值偏离",
            "平均估值偏离",
          ];
          /**
           * %
           * "单位中标量的销售佣金",
           **/

          const thousandMoney = ["价差损益", "财务损益", "总损益", "接入量"];
          const noUnit = [];
          const moneyUnit = ["万元", "亿元", "元"];
          for (var j = 0; j < params.length; j++) {
            res = params[j].seriesName;
            if (res == "债券只数") {
              lastName = "只";
            } else if (moneys.includes(res)) {
              lastName = "亿元";
              if (title == "当日持仓分析" && res == "持仓量") lastName = "万元";
            } else if (money.includes(res)) {
              lastName = "元";
            } else if (hour.includes(res)) {
              lastName = "天";
            } else if (BP.includes(res)) {
              lastName = "BP";
            } else if (thousandMoney.includes(res)) {
              lastName = "万元";
            } else {
              lastName = "%";
            }
            res1 += `<div class="tooptip-body">
                            <div class="tooptip-label">
                              <span class="tooptip-label-icon" style="background:linear-gradient(360deg, ${
                                params[j].color.colorStops[0].color
                              } 0%, ${
              params[j].color.colorStops[1].color
            } 100%);"></span>
                              <span>${res}</span>
                            </div>
                            <div>
                             <span class="tooptip-value">${
                               moneyUnit.includes(lastName)
                                 ? formatMoney(params[j].value)
                                 : params[j].value
                             }</span>
                             <span class="tooptip-unit">${lastName}</span>
                            </div>
                          </div>`;
          }
          var htmlStr = `
              <div class="tooptip-info">
                <div class="tooptip-title">${params[0].name}</div>
                <div class="tooptip-content">
                  ${res1}
                </div>
              </div>
            `;
          return htmlStr;
        };
        this.echarts1.setOption(options, true);
      }
      // let _this = this;
      // window.onresize = function() {
      //   setTimeout(() => {
      //     this.echarts1.resize();
      //   });
      // };
      setTimeout(() => {
        this.echarts1.resize();
      }, 500);
    },
  },
};
</script>

<style scoped lang="scss">
// 解决echarts resize不生效问题
::v-deep.box {
  width: 100%;
  height: 100%;
  min-height: 300px;
  // 子选择器(>) :只能选择作为某元素儿子元素的元素（直接子元素），不包括孙元素、曾孙元素等等等
  & > div:first-child {
    width: 100% !important;
    height: 100% !important;
    min-height: 300px;
    canvas {
      width: 100% !important;
      height: 100% !important;
      min-height: 300px;
    }
  }
}
</style>
